/*
 * Copyright (c)  2015~2020, xforceplus
 * All rights reserved.
 * Project:datacare-orm
 * Id: OrmObjectBuilder.java   2020-10-10 22-05-24
 * Author: Evan
 */
package cn.datacare.orm.mapping.orm;

import cn.datacare.orm.annotation.builder.ObjectSelectBuilder;
import cn.datacare.orm.mapping.lazy.LazyMappingEntity;
import cn.datacare.orm.source.SQLResult;
import cn.datacare.orm.source.SQLResultListener;
import cn.datacare.orm.source.SQLScript;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: 2015~2020
 * </p>
 * <p>
 * Company/Department: xforceplus
 * </p>
 *
 * @author Evan
 * <b>Creation Time:</b> 2020-10-10 22-05-24
 * @since V1.0
 */
public class OrmObjectBuilder implements ObjectSelectBuilder {


    @Override
    public void beforeSelect(Class target, SQLScript sqlScript, Annotation annotation, Map<String, Object> paras) {
        if (target == null || target == Map.class) {
            return;
        }

        OrmQuery ormQuery = (OrmQuery) target.getAnnotation(OrmQuery.class);
        if (ormQuery == null) {
            return;
        }

        OrmCondition[] conditions = ormQuery.value();

        Map<String, MappingEntity> map = new HashMap<>(1);

        for (OrmCondition cond : conditions) {
            MappingEntity mappingEntity = null;
            //类配合的orm查询总是
            if (cond.lazy()) {
                mappingEntity = new LazyMappingEntity();
            } else {
                mappingEntity = new MappingEntity();
            }
            mappingEntity.setSingle(cond.type() == OrmQuery.Type.ONE);
            mappingEntity.setTarget(cond.target().getName());
            if (cond.alias().length() != 0) {
                mappingEntity.setTailName(cond.alias());
            }

            mappingEntity.setSqlId(cond.sqlId().length() != 0 ? cond.sqlId() : null);
            Map<String, String> mapKey = new HashMap<>(1);
            mapKey.put(cond.attr(), cond.targetAttr());
            mappingEntity.setMapKey(mapKey);
            map.put(mappingEntity.getTarget(), mappingEntity);


        }

        //增加到listener,统一后处理映射关系
        OrmSqlResultListener orm = new OrmSqlResultListener();
        orm.getMappingEntities().addAll(map.values());
        List<SQLResultListener> sqlResultListeners = sqlScript.getListener();

        if (sqlResultListeners == null) {
            sqlResultListeners = new ArrayList<>();
        }

        sqlResultListeners.add(orm);
        sqlScript.setListener(sqlResultListeners);

    }

    @Override
    public List<Object> afterSelect(Class target, List<Object> entities, SQLScript sqlScript, Annotation annotation,
                                    SQLResult sqlResult) {
        return entities;

    }
}
